<template>
  <div>
    <!-- 面包屑导航 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 卡片视图 -->
      <el-card>
        <!-- 添加角色按钮 -->
        <el-button type="primary">添加角色</el-button>
        <!-- 角色列表 -->
        <el-table :data='roles' stripe border>
          <!-- 展开行 -->
          <el-table-column type='expand'>
            <template slot-scope="scope">
              <!-- 一级权限每一行（包含二级三级） -->
              <el-row class="border_bottom" :class="index === 0 ? 'border_top' : ''" v-for="(item, index) in scope.row.children" :key="item.id">
                <el-col :span='8'>
                  <el-tag>{{item.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 生成二级权限 -->
                <el-col :span='16'>
                  <!-- 二级权限每一行（包含三级） -->
                  <el-row :class="index2 === 0 ? '' : 'border_top'" v-for="(item2, index2) in item.children" :key="item2.id">
                    <el-col :span='5'>
                      <el-tag type='success'>{{item2.authName}}</el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <!-- 生成三级权限 -->
                    <el-col :span='19'>
                      <el-tag @close='removeTag(scope.row, item3.id)' closable v-for="item3 in item2.children" :key="item3.id" type='warning'>{{item3.authName}}</el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <!-- 索引 -->
          <el-table-column type='index' label="#">
          </el-table-column>
          <el-table-column prop="roleName" label="角色名称"></el-table-column>
          <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
          <el-table-column prop="data" label="操作" width="300">
            <!-- 包裹元素 -->
            <template slot-scope="scope">
              <el-button @click='rolesSetRights(scope.row)' type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
              <el-button @click="removeRoles(scope.row.id)" type="danger" icon="el-icon-delete" size="mini">删除</el-button>
              <el-button @click='showSetRights(scope.row)' type="warning" icon="el-icon-setting" size="mini">分配权限</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!-- 分配权限对话框 -->
      <el-dialog
        @close='closeSetDialog'
        title="分配权限"
        :visible.sync="SetRightsDialogVisible"
        width="50%">
        <!-- data 传递整个树形数据 -->
        <el-tree ref="tree" node-key='id' show-checkbox default-expand-all :default-checked-keys='defkeys' :data="rights" :props="treeDefaultProps"></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="SetRightsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="subSetRights">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑对话框 -->
      <el-dialog
        @close='rolesDialog'
        title="修改角色"
        :visible.sync="roleslogVisible"
        width="50%">
        <!-- ref 获取组件 DOM -->
        <el-form label-width="80px" :model="rolesForm" ref="rolesRef">
          <el-form-item label="角色名称" prop='roleName'>
            <el-input v-model="rolesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop='roleDesc'>
            <el-input v-model="rolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="roleslogVisible = false">取 消</el-button>
          <el-button type="primary" @click="rolesVisible">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 添加角色 -->
  </div>
</template>

<script>
export default {
  data () {
    return {
      roles: [],
      // 控制分配权限对话框显示
      SetRightsDialogVisible: false,
      // 接收所以权限列表树状数据
      rights: [],
      // 配置树型控件的配置对象
      treeDefaultProps: {
        // label 配置属性组件 显示文本的字段名
        label: 'authName'
      },
      // 设置树形默认选中
      defkeys: [],
      // 存储点击分配角色 id
      roleId: '',
      // 点击编辑对话框现实与隐藏
      roleslogVisible: false,
      // 编辑角色对象
      rolesForm: {
        roleName: '',
        roleDesc: ''
      }
    }
  },

  created () {
    this.getRoles()
  },

  methods: {
    // 获取角色列表数据
    async getRoles () {
      const { data: res } = await this.$axios.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取失败!')
      this.roles = res.data
    },
    // 点击关闭图标
    removeTag (row, rightId) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.delete(`roles/${row.id}/rights/${rightId}`)
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('删除失败!')
        row.children = res.data
        this.$message.success('删除成功!')
      }).catch(() => {
        this.$message('已取消删除')
      })
    },
    // 点击显示分类权限对话框
    async showSetRights (row) {
      this.SetRightsDialogVisible = true
      const { data: res } = await this.$axios.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取失败!')
      this.rights = res.data
      this.getAllKeys(row)
      this.roleId = row.id
    },
    getAllKeys (row) {
      if (!row.children) return this.defkeys.push(row.id)
      row.children.forEach(item => {
        this.getAllKeys(item)
      })
    },
    // 监视分配权对话框关闭
    closeSetDialog () {
      this.defkeys = []
    },
    // 提交权限分配
    async subSetRights () {
      // 获取所有的全选节点
      const checkedKeys = this.$refs.tree.getCheckedKeys()
      // 获取所有的半选节点
      const halfCheckedKeys = this.$refs.tree.getHalfCheckedKeys()
      // 整合所有权限id
      const rids = [...checkedKeys, ...halfCheckedKeys].join(',')
      const { data: res } = await this.$axios.post('roles/' + this.roleId + '/rights', { rids })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('更新失败!')
      this.$message.success('更新成功!')
      this.SetRightsDialogVisible = false
      this.getRoles()
    },
    // 点击显示编辑对话框
    rolesSetRights (item) {
      this.roleslogVisible = true
      // console.log(item)
      this.rolesForm = item
    },
    // 监听编辑对话框
    rolesDialog () {
      this.$refs.rolesRef.resetFields()
    },
    // 提交编辑角色
    rolesVisible () {
      this.$refs.rolesRef.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$axios.put('roles/' + this.rolesForm.id, {
          roleName: this.rolesForm.roleName,
          roleDesc: this.rolesForm.roleDesc
        })
        if (res.meta.status !== 200) return this.$message.error('提交失败!')
        this.$message.success('提交成功!')
        this.roleslogVisible = false
        this.getRoles()
      })
    },
    // 点击删除角色
    removeRoles (id) {
      this.$confirm('此操作将永久删除该角色', '是否继续?', '提示', {
        distinguishCancelAndClose: true,
        confirmButtonText: '保存',
        cancelButtonText: '放弃修改'
      }).then(async () => {
        const { data: res } = await this.$axios.delete('roles/' + id)
        if (res.meta.status !== 200) return this.$message.error('删除失败!')
        this.$message.success('删除成功!')
        this.getRoles()
      }).catch(action => {
        this.$message('已取消删除')
      })
    }
  }
}
</script>

<style scoped lang='less'>
  .el-tag {
    margin: 7px;
  }
  .border_top {
    border-top: 1px solid #eee
  }
  .border_bottom {
    border-bottom: 1px solid #eee
  }
  .el-row {
    display: flex;
    align-items: center;
  }
</style>
